package action;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.struts2.ServletActionContext;

import utils.CheckPhoneHelper;




import beans.Admin;
import beans.Company;
import beans.PackageInfo;

import com.opensymphony.xwork2.ActionSupport;

import dao.AdminDao;
import dao.CompanyDao;
import dao.PackageInfoDao;

/**
 * 
 * @author wjm
 * 
 */
@SuppressWarnings("serial")
public class PackageInfoAction extends ActionSupport {

	private File upload; // 在临时目录下的文件
	private String uploadContentType; // 文件类型
	private String expCompany;// 快递公司
	private Integer flag;
	private Integer count = 0; // 统计导入数据条数
	private Integer fail = 0; // 重复条数
	private String parcelID;
	private String message;
	private String funId;
	private String loginName;
	private String loginPwd;

	private List<Company> companies;
	private List<PackageInfo> packageInfos;
	private List<Admin> admins;

	PackageInfoDao dao = new PackageInfoDao();
	CompanyDao expDao = new CompanyDao();
	AdminDao adminDao = new AdminDao();

	public Integer getFail() {
		return fail;
	}

	public void setFail(Integer fail) {
		this.fail = fail;
	}

	public Integer getCount() {
		return count;
	}

	public void setCount(Integer count) {
		this.count = count;
	}

	public Integer getFlag() {
		return flag;
	}

	public void setFlag(Integer flag) {
		this.flag = flag;
	}

	public List<Company> getCompanies() {
		return companies;
	}

	public void setCompanies(List<Company> companies) {
		this.companies = companies;
	}

	public String getExpCompany() {
		return expCompany;
	}

	public void setExpCompany(String expCompany) {
		this.expCompany = expCompany;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getParcelID() {
		return parcelID;
	}

	public void setParcelID(String parcelID) {
		this.parcelID = parcelID;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public List<PackageInfo> getPackageInfos() {
		return packageInfos;
	}

	public void setPackageInfos(List<PackageInfo> packageInfos) {
		this.packageInfos = packageInfos;
	}

	public String getFunId() {
		return funId;
	}

	public void setFunId(String funId) {
		this.funId = funId;
	}

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getLoginPwd() {
		return loginPwd;
	}

	public void setLoginPwd(String loginPwd) {
		this.loginPwd = loginPwd;
	}

	public List<Admin> getAdmins() {
		return admins;
	}

	public void setAdmins(List<Admin> admins) {
		this.admins = admins;
	}

	/**

	 * 文件上传及解析写入数据库
	 * 
	 * @return
	 */
	public String packageLoad() {
		if (expCompany == null) {
			flag = 3;
			return "packageInfoLoad";
		}
		// System.out.println(uploadContentType+"-----------------------------------------------dfghdfhf");
		if (!uploadContentType.equals("text/html")) {
			flag = 2;
			return "packageInfoLoad";
		}
		try {
			// 文件上传
			InputStream in = new FileInputStream(upload);

			// String dir =
			// ServletActionContext.getServletContext().getRealPath(
			// "upload");
			File file = new File("/www/upload_html");
			if (!file.exists()) {
				file.mkdirs();
			}

			File uploadFile = new File("/www/upload_html", "load.html");

			OutputStream out = new FileOutputStream(uploadFile);

			byte[] buffer = new byte[1024 * 1024];

			int length;

			while ((length = in.read(buffer)) > 0) {

				out.write(buffer, 0, length);

			}
			in.close();

			out.close();
			// 获取上传的文件路径不包括文件名
			String url = uploadFile.getPath().substring(0,
					uploadFile.getPath().length() - 9);
			StringBuffer sb = new StringBuffer();
			// 获取指定tm网页的内容
			BufferedReader br = new BufferedReader(
					new InputStreamReader(new FileInputStream(new File(url
							+ "/load.html")), "GB2312"));
			String line = br.readLine();
			while (line != null) {
				sb.append(line);
				line = br.readLine();
			}
			br.close();
			// 将获取的内容写入指定的html
			PrintWriter pw = new PrintWriter(new File(url + "/table.html"),
					"GB2312");
			Pattern p = Pattern.compile("<table .*?>*</table>");
			Matcher m = p.matcher(sb);
			List<Object> list = new ArrayList<Object>(); // 存入页面内容集合
			while (m.find()) {
				list.add(m.group());
			}
			pw.println(list.get(0)); // 写入要获取的table
			// System.out.println(list.get(0));
			pw.close();
			// ---------------------------------第二次读取
			StringBuffer sb1 = new StringBuffer();
			BufferedReader br1 = new BufferedReader(new InputStreamReader(
					new FileInputStream(new File(url + "/table.html")),
					"GB2312"));
			String line1 = br1.readLine();
			while (line1 != null) {
				sb1.append(line1);
				line1 = br1.readLine();
			}
			br1.close();
			PrintWriter pw1 = new PrintWriter(new File(url + "/td.html"),
					"GB2312");
			Pattern p1 = Pattern.compile("<tr>[\\s\\S]*?</tr>");
			Matcher m1 = p1.matcher(sb1);
			List<Object> list1 = new ArrayList<Object>();
			while (m1.find()) {
				list1.add(m1.group());
				pw1.println(m1.group());
			}
			List<Map<String, String>> result = new ArrayList<Map<String, String>>(); // 将表格的内容和表头做为map集合存入
			List<String> key = new ArrayList<String>();// 存入表格表头做为key
			List<String> value = new ArrayList<String>();// 存入表格内容做为value
			for (int i = 0; i < list1.size(); i++) {
				if (i == 0) {
					String str = list1.get(i).toString();// 获取指定的表头的文字
					// System.out.println(str);
					String[] str1 = str.split("<b>");
					for (int j = 1; j < str1.length; j++) {
						String string = str1[j].substring(0,
								str1[j].indexOf("</b>"));
						// System.out.println(string);
						key.add(string);

					}
				} else {
					value.add(list1.get(i).toString());
				}
			}
			for (int i = 0; i < value.size(); i++) {
				String string = value.get(i);
				Map<String, String> map = new HashMap<String, String>();
				String[] str = string.split("</td>");
				for (int j = 0; j < str.length - 1; j++) {
					String str1 = str[j];
					if (str[j].indexOf("</a>") >= 0) {
						str1 = str[j].substring(str[j].lastIndexOf("<a"),
								str[j].lastIndexOf("</a>"));
						str1 = str1.substring(str1.lastIndexOf(">") + 1);
					} else {
						str1 = str[j].substring(str[j].lastIndexOf(">") + 1);
					}
					// System.out.println(str1);
					map.put(key.get(j), str1);
				}
				result.add(map);
			}
			pw1.close(); // 关闭流
			List<PackageInfo> pack = new ArrayList<PackageInfo>();
			List<PackageInfo> pack1 = dao.getAllPackageInfo();
			for (int i = 0; i < result.size(); i++) {
				if (result.get(i).get("收件人电话").trim().equals("")
						|| !CheckPhoneHelper.isMobileNO(result.get(i)
								.get("收件人电话").trim())) {
					fail++;
					continue;
				}
				PackageInfo packageinfo = new PackageInfo(result.get(i).get(
						"寄件人"), result.get(i).get("寄件地址"), result.get(i).get(
						"寄件人电话"), result.get(i).get("收件人"), result.get(i).get(
						"收件地址"), result.get(i).get("收件人电话"), result.get(i).get(
						"运单编号"), result.get(i).get("重量").trim().equals("") ? 0
						: Float.parseFloat(result.get(i).get("重量")),
						expCompany, "0", result.get(i).get("签收备注") == null ? ""
								: result.get(i).get("签收备注"));
				if (pack1.size() > 0) {
					boolean bool = false;
					for (int j = 0; j < pack1.size(); j++) {
						if (pack1.get(j).getPackNum()
								.equals(packageinfo.getPackNum())) {
							fail++;
							bool = true;
							break;
						}
					}
					if (bool == false) {
						pack.add(packageinfo);
						count++;
					}
				} else {
					pack.add(packageinfo);
					count++;
				}
			}
			dao.saveListOfPackageInfo(pack);
			// count=map.get("count");
			// fail=map.get("fail");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			flag = 0;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			flag = 0;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			flag = 0;
		}
		flag = 1;
		return "packageInfoLoad";
	}

	/**
	 * 获取expCompany名称
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getExpCompanyAll() throws Exception {
		companies = expDao.getAllcompany();
		return "selectCompany";
	}

	private List<File> uploadfiles;
	
	
	public List<File> getUploadfiles() {
		return uploadfiles;
	}

	public void setUploadfiles(List<File> uploadfiles) {
		this.uploadfiles = uploadfiles;
	}
	

/**
    * 批量上传
    * @return
    */
	public String uploadFiles(){
		if (expCompany == null) {
			flag = 3;
			return "packageInfoLoad";
		}
		List<PackageInfo> pack1 = dao.getAllPackageInfo();
		for (File files : uploadfiles) {
			try {
				// 文件上传
				InputStream in = new FileInputStream(files);
				File file = new File("/www/upload_html");
				if (!file.exists()) {
					file.mkdirs();
				}

				File uploadFile = new File("/www/upload_html", "load.html");

				OutputStream out = new FileOutputStream(uploadFile);

				byte[] buffer = new byte[1024 * 1024];

				int length;

				while ((length = in.read(buffer)) > 0) {

					out.write(buffer, 0, length);

				}
				in.close();

				out.close();
				// 获取上传的文件路径不包括文件名
				String url = uploadFile.getPath().substring(0,
						uploadFile.getPath().length() - 9);
				StringBuffer sb = new StringBuffer();
				// 获取指定tm网页的内容
				BufferedReader br = new BufferedReader(
						new InputStreamReader(new FileInputStream(new File(url
								+ "/load.html")), "GB2312"));
				String line = br.readLine();
				while (line != null) {
					sb.append(line);
					line = br.readLine();
				}
				br.close();
				// 将获取的内容写入指定的html
				PrintWriter pw = new PrintWriter(new File(url + "/table.html"),
						"GB2312");
				Pattern p = Pattern.compile("<table .*?>*</table>");
				Matcher m = p.matcher(sb);
				List<Object> list = new ArrayList<Object>(); // 存入页面内容集合
				while (m.find()) {
					list.add(m.group());
				}
				pw.println(list.get(0)); // 写入要获取的table
				// System.out.println(list.get(0));
				pw.close();
				// ---------------------------------第二次读取
				StringBuffer sb1 = new StringBuffer();
				BufferedReader br1 = new BufferedReader(new InputStreamReader(
						new FileInputStream(new File(url + "/table.html")),
						"GB2312"));
				String line1 = br1.readLine();
				while (line1 != null) {
					sb1.append(line1);
					line1 = br1.readLine();
				}
				br1.close();
				PrintWriter pw1 = new PrintWriter(new File(url + "/td.html"),
						"GB2312");
				Pattern p1 = Pattern.compile("<tr>[\\s\\S]*?</tr>");
				Matcher m1 = p1.matcher(sb1);
				List<Object> list1 = new ArrayList<Object>();
				while (m1.find()) {
					list1.add(m1.group());
					pw1.println(m1.group());
				}
				List<Map<String, String>> result = new ArrayList<Map<String, String>>(); // 将表格的内容和表头做为map集合存入
				List<String> key = new ArrayList<String>();// 存入表格表头做为key
				List<String> value = new ArrayList<String>();// 存入表格内容做为value
				for (int i = 0; i < list1.size(); i++) {
					if (i == 0) {
						String str = list1.get(i).toString();// 获取指定的表头的文字
						// System.out.println(str);
						String[] str1 = str.split("<b>");
						for (int j = 1; j < str1.length; j++) {
							String string = str1[j].substring(0,
									str1[j].indexOf("</b>"));
							// System.out.println(string);
							key.add(string);

						}
					} else {
						value.add(list1.get(i).toString());
					}
				}
				for (int i = 0; i < value.size(); i++) {
					String string = value.get(i);
					Map<String, String> map = new HashMap<String, String>();
					String[] str = string.split("</td>");
					for (int j = 0; j < str.length - 1; j++) {
						String str1 = str[j];
						if (str[j].indexOf("</a>") >= 0) {
							str1 = str[j].substring(str[j].lastIndexOf("<a"),
									str[j].lastIndexOf("</a>"));
							str1 = str1.substring(str1.lastIndexOf(">") + 1);
						} else {
							str1 = str[j].substring(str[j].lastIndexOf(">") + 1);
						}
						// System.out.println(str1);
						map.put(key.get(j), str1);
					}
					result.add(map);
				}
				pw1.close(); // 关闭流
				List<PackageInfo> pack = new ArrayList<PackageInfo>();
				
				for (int i = 0; i < result.size(); i++) {
					if (result.get(i).get("收件人电话").trim().equals("")
							|| !CheckPhoneHelper.isMobileNO(result.get(i)
									.get("收件人电话").trim())) {
						fail++;
						continue;
					}
					PackageInfo packageinfo = new PackageInfo(result.get(i).get(
							"寄件人"), result.get(i).get("寄件地址"), result.get(i).get(
							"寄件人电话"), result.get(i).get("收件人"), result.get(i).get(
							"收件地址"), result.get(i).get("收件人电话"), result.get(i).get(
							"运单编号"), result.get(i).get("重量").trim().equals("") ? 0
							: Float.parseFloat(result.get(i).get("重量")),
							expCompany, "0", result.get(i).get("签收备注") == null ? ""
									: result.get(i).get("签收备注"));
					if (pack1.size() > 0) {
						boolean bool = false;
						for (int j = 0; j < pack1.size(); j++) {
							if (pack1.get(j).getPackNum()
									.equals(packageinfo.getPackNum())) {
								fail++;
								bool = true;
								break;
							}
						}
						if (bool == false) {
							pack.add(packageinfo);
							count++;
						}
					} else {
						pack.add(packageinfo);
						count++;
					}
				}
				dao.saveListOfPackageInfo(pack);
				// count=map.get("count");
				// fail=map.get("fail");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				flag = 0;
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				flag = 0;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				flag = 0;
			}
		}
		flag = 1;
		return "packageInfoLoad";
	}
	
	
	/**
	 * 获取文件的扩展名，如：aa.jpg，获得.jpg
	 * @param fileName
	 * @return
	 */
	private String ext(String fileName){
		int pos = fileName.lastIndexOf('.');
		
		if(pos == -1){
			return "";
		}else{
			return fileName.substring(pos);
		}
	}

}
